﻿using BlazorOrdering.Core;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlazorOrdering.Application
{
    public class BoMenuService : IBoMenuService, ITransient, IDynamicApiController
    {
        //private readonly IDbContextFactory<DefaultDbContext> _contextFactory;

        private readonly IRepository<BoMenu> _menuRepository;

        public BoMenuService(IRepository<BoMenu> menuRepository)
        {
            _menuRepository = menuRepository;
            //_contextFactory = contextFactory;//注入工厂

        }

        /// <summary>
        /// 返回当前日期以后的菜谱，供修改编辑使用
        /// </summary>
        /// <param name="day">指定日期</param>
        /// <returns></returns>
        public Task<List<BoMenu>> GetAllMenusAsync(DateTime? day)
        {
            //var menus = _menuRepository.Where(m => m.Day >= day)
            //                            .OrderBy(m => m.Day)
            //                            .ToList();


            using (var dbContext = Db.GetNewDbContext())
            //using (var dbContext = _contextFactory.CreateDbContext())
            {
                var menus = dbContext.Set<BoMenu>().Where(m => m.Day >= day)
                                        .OrderBy(m => m.Day)
                                        .ToList();
                return Task.FromResult(menus.Adapt<List<BoMenu>>());
            }




        }


        /// <summary>
        /// 返回指定日期前一天及后面所有日期的菜谱
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        public Task<List<BoMenu>> GetMenus4ShowAsync(DateTime? day)
        {
            if (day is null)
            {
                day = DateTime.Now.Date.AddDays(-1);
            }
            else
            {
                day = Convert.ToDateTime(day).AddDays(-1);
            }
            //var menus = _menuRepository.Where(m => m.Day >= day)
            //                            .OrderBy(m => m.Day)
            //                            .ThenBy(m => m.Type);
            //return Task.FromResult(menus.Adapt<List<BoMenu>>());

            using (var dbContext = Db.GetNewDbContext())
            //using (var dbContext = _contextFactory.CreateDbContext())
            {
                var menus = dbContext.Set<BoMenu>().Where(m => m.Day >= day)
                                        .OrderBy(m => m.Day)
                                        .ThenBy(m => m.Type);

                return Task.FromResult(menus.Adapt<List<BoMenu>>());
            }
        }
        /// <summary>
        /// 返回指定日期的菜谱
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        public Task<List<BoMenu>> GetMenusAsync(DateTime? day)
        {
            if (day is null)
            {
                day = DateTime.Now.Date;
            }
            //var menus = _menuRepository.Where(m => m.Day == day).ToList();

            //return Task.FromResult(menus.Adapt<List<BoMenu>>());


            //使用 DbContext 工厂 新建context 解决线程之间共享上下文冲突问题
            using (var dbContext = Furion.DatabaseAccessor.Db.GetNewDbContext())
            //using (var dbContext = _contextFactory.CreateDbContext())
            {
                var menus = dbContext.Set<BoMenu>().Where(m => m.Day == day).ToList();

                return Task.FromResult(menus.Adapt<List<BoMenu>>());
            }


            //using (var dbContext = Furion.DatabaseAccessor.Db.GetNewDbContext())
            //{
            //    //Blazor不同组件调用这个方法获取到的 dbContext 是不是同一个呢？
            //    //代码地址：https://gitee.com/KongQiWai/blazor-ordering/blob/master/BlazorOrdering.Web.Core/Data/BoMenuService.cs
            //    // DbContext 并非线程安全，但在用户线路中的各个组件之间共享
            //    // https://docs.microsoft.com/zh-cn/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-5.0
            //    var menus = dbContext.Set<BoMenu>().Where(m => m.Day == day).ToList();

            //    return Task.FromResult(menus.Adapt<List<BoMenu>>());
            //}
        }

        public string AddOne(BoMenu bomeun)
        {
            var newEntity = _menuRepository.InsertNow(bomeun);
            if (newEntity != null)
            {
                return "ok";
            }
            else
            {

                return "添加菜谱失败，请联系系统管理员";
            }
        }

        public Task<string> Update(BoMenu bomeun)
        {
            if (bomeun.Id < 1)
            {
                return Task.FromResult("数据库中不存在此菜谱，修改失败，请联系管理员");
            }
            //bomeun 为前台传来的，不被仓储跟踪的实体
            //先查到它，再更新它
            //根据 ID 查找数据库中的实体
            var findit = _menuRepository.Find(bomeun.Id);
            if (findit != null)
            {
                //这里怎样将 前台传来的实体的所有属性赋值给 数据库中的实体呢？
                //findit.Name = bomeun.Name;
                //findit.Price = bomeun.Price;
                //findit.Type = bomeun.Type;

                //var dto = entity.Adapt<Dto>();
                findit = bomeun.Adapt<BoMenu>(); //Mapster 就可以了

                var newEntity = _menuRepository.UpdateExistsNowAsync(findit);
                if (newEntity != null)
                {
                    return Task.FromResult("ok");
                }
                else
                {

                    return Task.FromResult("修改菜谱失败，请联系系统管理员");
                }
            }
            else
            {
                return Task.FromResult("数据库中不存在此菜谱，修改失败，请联系系统管理员");
            }
        }

        public Task<string> Del(BoMenu bomeun)
        {
            //_menuRepository.DeleteExists(bomeun.Id);
            //_menuRepository.DeleteNow(bomeun.Id); //执行完毕并没有删除？？

            var meun = _menuRepository.Find(bomeun.Id);
            if (meun != null)
            {
                _menuRepository.DeleteNow(meun);
                return Task.FromResult("ok");
            }
            else
            {
                return Task.FromResult("删除操作失败了！");
            }

        }
    }
}
